package org.springframework.nio.handler.adapter;

import java.lang.reflect.Method;

import org.springframework.nio.NioRequest;
import org.springframework.nio.method.HandlerMethod;

public class DefaultHandlerAdapter extends AbstractHandlerAdapter {


	@Override
	public boolean supportInternal(HandlerMethod handler) {
		return true;
	}

	@Override
	public Object handleInternal(NioRequest<?> request, HandlerMethod handler)
			throws Exception {
		Object controllerBean = handler.getBean();
		Method method = handler.getMethod();
		
		Class<?>[] clazzes = method.getParameterTypes();
		Object[] params = new Object[clazzes.length];
		for(int i=0;i<clazzes.length;i++){
			Class<?> clazz = clazzes[i];
			if(clazz.isInstance(request)){
				params[i] = request;
			}else if(request.hasBody() && clazz.isInstance(request.getBody())){
				params[i] = request.getBody();
			}else if(clazz.isInstance(request.getHead())){
				params[i] = request.getHead();
			}else if(clazz.isInstance(request.getHandler())){
				params[i] = request.getHandler();
			}else {
				params[i] = null;
			}
		}
		return method.invoke(controllerBean, params);
		
	
	}

}
